<template>
  <div fluid grid-list-md class="agent-query-container">
    <v-container fluid fill-height>
      <v-layout justify-center align-start wrap>
        <v-flex xs12 md12>
          <v-btn color="green darken-1" dark @click="dialog = true">
            <span class="mx-1">添加文章</span>
            <v-icon color="white">add</v-icon>
          </v-btn>
        </v-flex>
        <v-flex text-xs-center md12 xs12>
          <v-data-table :headers="headers" :items="tableData" hide-actions class="elevation-1">
            <template slot="items" slot-scope="props">
              <td class="text-xs-center subheading">{{ props.item.title }}</td>
              <td class="text-xs-center subheading">{{ props.item.source }}</td>
              <td class="text-xs-center subheading">{{ props.item.content.substring(0, 10) }}</td>
              <td class="text-xs-center">
                <v-btn flat round dark color="blue darken-1" class="mx-1" @click="gotoDetails(props.item)">
                  <span class="mx-1">详情</span>
                  <v-icon color="blue darken-1">assignment</v-icon>
                </v-btn>
                <v-btn flat round dark color="red darken-1" class="mx-1" @click="deleteArticle(props.item)">
                  <span class="mx-1">删除</span>
                  <v-icon color="red darken-1">delete_forever</v-icon>
                </v-btn>
              </td>
            </template>
            <template slot="no-data">
              <div class="text-md-center">
                <v-icon color="yellow darken-3">warning</v-icon>
                <span class="subheading">请添加文章数据</span>
              </div>
            </template>
          </v-data-table>
        </v-flex>
      </v-layout>
      <v-dialog v-model="dialog" persistent max-width="1080px">
        <v-card>
          <v-card-title>
            <span class="headline">添加文章</span>
          </v-card-title>
          <v-card-text>
            <v-container grid-list-md>
              <v-layout justify-center align-start wrap>
                <v-flex text-xs-center md12>
                  <v-text-field label="标题" solo v-model="articleTitle"></v-text-field>
                </v-flex>
                <v-flex text-xs-center md6>
                  <v-text-field label="副标题" solo v-model="articleSubTitle"></v-text-field>
                </v-flex>
                <v-flex xs12 sm3 md3>
                  <v-select v-model="articleType" :items="typeItems" label="类别" required></v-select>
                </v-flex>
                 <v-flex md3 xs3 d-flex>

                    <v-btn color="red" class="white--text input-wrapper">
                      <v-icon right dark>add</v-icon>
                      <span>选择图片</span>
                      <input @change="imageInputHandler" name="files" type="file" accept="image/jpg" ref="imageInput" class="file-input">
                    </v-btn>
                  </v-flex>
                <v-flex xs12 md12>
                <v-layout justify-start align-start>
                 
                                      <!-- <v-btn color="red" class="white--text" @click="addAnImage">
                  图片
                  <v-icon right dark>add</v-icon>
                      </v-btn>-->
                    <!-- <v-btn cvolor="light-blue" class="white--text" @click="uploadArticle">上传
                      <v-icon right dark>cloud_upload</v-icon>
                    </v-btn> -->
                    <!-- <v-btn color="cyan darken-2" class="white--text" @click="previewArticle">
                  预览
                  <v-icon right dark>more</v-icon>
                </v-btn>
                <v-btn color="cyan darken-2" class="white--text" @click="getArticleList">
                  获取
                  <v-icon right dark>more</v-icon>
                      </v-btn>-->
                    <!-- <v-btn color="indigo darken-2" class="white--text" @click="boldenText">
                  粗体
                  <v-icon right dark>more</v-icon>
                      </v-btn>-->
                </v-layout>
                </v-flex>
                <v-flex md12>
                <v-layout justify-start align-start>
                  <!-- <v-flex md6 xs6>
                <v-textarea solo rows="30" name="articleContent" label="内容" v-model="articleContent">
                </v-textarea>
              </v-flex>@blur="onEditorBlur($event)"
                      @focus="onEditorFocus($event)"
                    @ready="onEditorReady($event)"-->
                  <v-flex md6 xs6>
                    <!-- <v-textarea solo rows="30" ref="articleEditbox" id="article-editbox" name="articleContent" label="内容" v-model="articleContent">
                      </v-textarea>-->
                    <div class="article-content elevation-2" ref="articleEditbox" contenteditable="plaintext-only"></div>
                  </v-flex>
                  <v-flex md6 xs6>
                    <v-layout class="article-content elevation-2" row nowrap justify-space-between>
                      <v-flex md6 xs6>
                        <ul class="image-list">
                          <li v-for="(img, i) of imageList" :key="i">
                            <img :src="img.src" alt class="image-list-item">
                            <span class="image-list-name">{{img.name}}</span>
                            <v-btn @click="deleteImage(img)" icon dark>
                              <v-icon color="red">delete_forever</v-icon>
                            </v-btn>
                          </li>
                        </ul>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                </v-layout>
                </v-flex>
                </v-flex>
              </v-layout>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="red darken-1" round dark flat @click="dialog = false">取消</v-btn>
            <v-btn color="blue darken-1" round dark flat @click="confirmDialog">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </div>
</template>
<script>
import axios from "../api";
import { article } from "../api/request";
import { mapMutations } from "vuex";
export default {
  data: () => ({
    limit: 10,
    offset: 0,
    articleTitle: "",
    articleSubTitle: "",
    articleContent: "",
    iamgeIndex: 0,
    imageName: "",
    currentImage: { name: "" },
    markedArticle: "",
    transArticle: "",
    dialog: false,
    imageList: [],
    tableData: [],
    headers: [
      { text: "标题", value: "lftid", align: "center", sortable: false },
      { text: "副标题", value: "headUrl", align: "center", sortable: false },
      { text: "内容", value: "nickname", align: "center", sortable: false },
      { text: "操作", value: "actions", align: "center", sortable: false }
    ],
    typeItems: [{
      text: '热门',
      value: 1
    }, {
      text: '攻略',
      value: 2
    }, {
      text: '英雄',
      value: 3
    }],
    articleType: 1
  }),
  mounted() {
    this.getArticleList()
  },
  methods: {
    gotoPage(value) {
      this.drawerSwitch = value;
    },
    gotoDetails(item) {},
    deleteArticle(item) {},
    confirmDialog() {
      this.uploadArticle()
    },
    boldenText() {
      let sel = window.getSelection();
      let str = sel.toString();
      // 获取选中的索引位置
      let { anchorOffset, focusOffset } = sel;
      let content = document.getElementById("marked-article").innerHTML;
      console.log(content);
      if (str) {}
    },
    uploadArticle() {
      let content = this.stringifyArticle(
        this.$refs.articleEditbox.textContent
      );
      console.log(content);
      let form = new FormData();
      form.append("title", this.articleTitle);
      form.append("source", this.articleSubTitle);
      form.append("content", content);
      // let imgs = [];
      this.imageList.forEach((item, i) => {
        form.append([`image${i}`], item.file);
        // imgs.push(item.file);
      });
      // form.append('pictureUrl', imgs);
      form.append("type", this.articleType);
      form.append("star", 0);
      form.append("likes", 0);
      // form.append('files', imgs);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      console.error(form);
      article.uploadArticle.r(form, config).then(({ data }) => {
        console.log('uploadArticle', data);
        this.dialog = false;
        alert(data.message);

        this.$refs.articleEditbox.textContent = '';
        this.articleTitle = '';
        this.articleSubTitle = '';
        this.articleType = 1;
        this.imageList = []
      });
    },
    dropImage(ev) {
      ev.preventDefault();
      console.error(ev);
    },
    getArticleList() {
      let opt = {
        // offset: 0,
        // limit: 10
      };
      article.getArticleList
        .r(opt)
        .then(({ data }) => {
          this.tableData = data.data.dataList;
          console.log("getArticleList", data);
        })
        .catch(err => {
          console.error(err);
        });
    },
    previewArticle() {
      // this.transArticle = this.stringifyArticle(this.articleContent)
      // let content = this.$refs.articleEditbox.innerText;
      // this.markedArticle = this.stringifyArticle(content);
      // this.markedArticle = this.markdown(this.articleContent);
      // let ma = document.getElementById('marked-article');
      // console.log(articleContent)
      let res = this.stringifyArticle(this.$refs.articleEditbox.textContent);
    },
    addAnImage() {
      let img = this.currentImage;
      // if (!img) {
      //   return alert('请选择图片');
      // }
      // let sel = window.getSelection();
      // console.log(sel)
      // this.articleContent += `\n![](${img.name})\n`
      this.imageList.push(this.currentImage);

      // let preUrl = 'https://www.xxxx.com/image/';
      // this.articleContent += `![${img}](${preUrl}${img})`;
    },
    // 插入图片的md标记
    insertString(img) {
      let box = this.$refs.articleEditbox;
      this.$refs.articleEditbox.focus();
      let sel = window.getSelection();
      let { anchorNode, anchorOffset, focusOffset, rangeCount, type } = sel;
      console.error(anchorOffset, focusOffset, rangeCount, sel);
      let result;
      // if(sel.anchorNode.id == 'article-editbox') {
      result = anchorNode.textContent.substring(anchorOffset + 1, focusOffset);
      // }
      // 获取分隔的范围
      let firstPart = anchorNode.textContent.slice(0, anchorOffset);
      let lastPart = anchorNode.textContent.slice(
        anchorOffset,
        anchorNode.textContent.length
      );
      // 光标Caret 选中了范围Range
      box.textContent += `\n![](${img})\n`;
      // if(type === 'Caret') {
      //   box.textContent = firstPart + `\n![](${img})\n` + lastPart;
      // }else if(type === 'Range') {
      //   box.textContent = box.textContent.replace(result, `\n![](${img})\n`)
      // }
    },
    imageInputHandler(ev) {
      let file = ev.target.files[0];
      let fr = new FileReader();
      let that = this;
      fr.onload = res => {
        // console.error(res);
        let result = res.target.result;
        this.currentImage = {
          name: file.name,
          file: file,
          src: result
        };
        this.insertString(file.name);
        this.imageList.push(this.currentImage);
        // console.log(this.currentImage)
        // that.markedArticle += `<img src=${result} alt="555"/>`
      };
      fr.readAsDataURL(file);
    },
    deleteImage(img) {
      let index = -1;
      this.imageList.forEach((item, i) => {
        if (item.name === img.name) {
          index = i;
        }
      });
      if (index !== -1) {
        this.imageList.splice(index, 1);
      }
    },
    stringifyArticle(content) {
      // console.log(JSON.stringify(content).replace(/\\n/g, '<br/>'))
      let strongEx = /\*\*([^(\n|\*)]*)\*\*/g;
      let strongArr = content.match(strongEx);
      if (strongArr) {
        strongArr.forEach(item => {
          let con = item.substring(2, item.length - 2);
          content = content.replace(item, `<strong>${con}</strong>`);
        });
      }

      // let imageEx = /\!\[[^(\[|\]|\s|\n)]\]\([^\s\n]\)/g
      // let imageArr = content.match(imageEx);
      // console.log(imageArr)

      let imageEx = /!\[[^\n]*\]\([^\n]*\)/g;
      let imageArr = content.match(imageEx);
      if (imageArr) {
        imageArr.forEach(item => {
          let href = item.replace(/(!|\[|\]|\(|\))/g, "");
          content = content.replace(
            item,
            `<br/><img src=\&quot;${href}\&quot;/>`
          );
        });
      }
      let result = JSON.stringify({ content });
      result = result.replace(/\\n/g, "<br/>");
      // result = result.replace(/\"/g, '\&quot;');
      return JSON.parse(result).content.replace(/\"/g, "&quot;");
    }
  }
};
</script>
<style lang="less" scoped>
#marked-article {
  text-align: left;
  font-size: 18px;
  padding: 0.8rem 1rem;
  height: 100%;
}

img {
  width: 100%;
}

.article-content {
  min-height: 12em;
  width: 100%;
  text-align: left;
  padding: 1em;
  font-size: 1.2rem;
}

.image-list {
    display: flex;
  justify-content: space-around;
  li {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    list-style: none;

    .image-list-item {
      width: 5rem;
          height: 5rem;
    }

    .image-list-name {
      font-size: 1rem;
    }
  }
}

.input-wrapper {
  display: inline-block;
  position: relative;

  // width: 6rem;
  // height: 3.2rem;
  // border: 2px dashed #5ff44a;
  // border-radius: 4px;
  .file-input {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
  }
}
</style>